package com.ruoyi.web.controller.flowable;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.ApplyDTO;
import com.ruoyi.system.domain.dto.HandleDataDTO;
import com.ruoyi.system.domain.dto.StartProcessInstanceDTO;
import com.ruoyi.system.domain.dto.TaskDTO;
import com.ruoyi.system.domain.vo.HandleDataVO;
import com.ruoyi.system.domain.vo.HistoryProcessInstanceVO;
import com.ruoyi.system.domain.vo.TaskDetailVO;
import com.ruoyi.system.domain.vo.TaskVO;
import com.ruoyi.system.service.*;
import io.swagger.annotations.ApiOperation;
import org.flowable.engine.HistoryService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 工作流
 */
@RestController
@RequestMapping("/flowable/workspace")
public class WorkspaceProcessController extends BaseController {

    @Resource
    private WorkspaceProcessService workspaceProcessService;
    @Resource
    private HistoryService historyService;
    @Resource
    private TaskService taskService;

    /**
     * 查询用户可以发起的流程模板
     */
    @PostMapping("/groupTemplatelist")
    public TableDataInfo list(@RequestBody SysUser sysUser)
    {
        List<FormGroups> formGroups = workspaceProcessService.selectFormGroupsListByUserId(sysUser);
        return getDataTable(formGroups);
    }


    /**
     * 通过模板id查看流程信息 会附带流程定义id
     */
    @PostMapping("/process/templateInfo")
    public AjaxResult detail(@RequestBody ProcessTemplates processTemplate){
        String templateId = processTemplate.getTemplateId();
        ProcessTemplates processTemplates = workspaceProcessService.selectProcessTemplatesByTemplateId(templateId);
        return success(processTemplates);
    }


    /**
     * 通过流程定义id启动流程
     */
    @ApiOperation("通过流程定义id启动流程")
    @PostMapping("/process/start")
    public AjaxResult start(@RequestBody StartProcessInstanceDTO startProcessInstanceDTO){
        return workspaceProcessService.startProcess(startProcessInstanceDTO);
    }


    /**
     * 查看抄送
     * @param taskDTO 当前登陆人信息
     */
    @PostMapping("/process/ccList")
    public TableDataInfo ccList(@RequestBody TaskDTO taskDTO){

        //查询用户的抄送数据
        Integer pageNo = taskDTO.getPageNo();
        Integer pageSize = taskDTO.getPageSize();
        String userId = taskDTO.getCurrentUserInfo().getId();
        setStartPage(pageNo,pageSize);
        ApproveCarbonCopy approveCarbonCopy = new ApproveCarbonCopy();
        approveCarbonCopy.setUserId(Long.valueOf(userId));
        List<ApproveCarbonCopy> approveCarbonCopies = workspaceProcessService.selectCCList(approveCarbonCopy);
        return getDataTable(approveCarbonCopies);
    }


    /**
     * 查看我发起的流程
     */
    @PostMapping("/process/applyList")
    public TableDataInfo applyList(@RequestBody ApplyDTO applyDTO){
        String userId = applyDTO.getCurrentUserInfo().getId();
        //查询发起的流程实例列表
        List<HistoricProcessInstance> historicProcessInstances =
                historyService.createHistoricProcessInstanceQuery()
                        .includeProcessVariables()
                        .startedBy(userId)
                        .orderByProcessInstanceStartTime().desc()
                        .listPage((applyDTO.getPageNo() - 1) * applyDTO.getPageSize(), applyDTO.getPageSize());
        long count = historyService.createHistoricProcessInstanceQuery()
                .startedBy(applyDTO.getCurrentUserInfo().getId()).count();
        List<HistoryProcessInstanceVO> historyProcessInstanceVOS = workspaceProcessService.applyList(historicProcessInstances);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(historyProcessInstanceVOS);
        rspData.setTotal(count);
        return rspData;
    }


    /**
     * 查看我的待办
     */
    @PostMapping("/process/toDoList")
    public TableDataInfo toDoList(@RequestBody TaskDTO taskDTO){
        List<Task> tasks = taskService.createTaskQuery().taskAssignee(taskDTO.getCurrentUserInfo().getId())
                .includeProcessVariables()
                .orderByTaskCreateTime().desc()
                .listPage((taskDTO.getPageNo() - 1) * taskDTO.getPageSize(), taskDTO.getPageSize());
        long count = taskService.createTaskQuery().taskAssignee(taskDTO.getCurrentUserInfo().getId()).count();
        List<TaskVO> taskVOS = workspaceProcessService.toDoList(tasks);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(taskVOS);
        rspData.setTotal(count);
        return rspData;
    }

    /**
     * 查看我的已办
     */
    @PostMapping("/process/doneList")
    public TableDataInfo doneList(@RequestBody TaskDTO taskDTO){
        List<HistoricTaskInstance> tasks = historyService.createHistoricTaskInstanceQuery()
                .taskAssignee(taskDTO.getCurrentUserInfo().getId())
                .finished()
                .includeProcessVariables()
                .orderByTaskCreateTime().desc()
                .listPage((taskDTO.getPageNo() - 1) * taskDTO.getPageSize(), taskDTO.getPageSize());
        long count = historyService.createHistoricTaskInstanceQuery()
                .taskAssignee(taskDTO.getCurrentUserInfo().getId()).finished().count();
        List<TaskVO> taskVOS = workspaceProcessService.doneList(tasks);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(taskVOS);
        rspData.setTotal(count);
        return rspData;
    }

    /**
     * 同意按钮
     */
    @PostMapping("/agree")
    public AjaxResult agree(@RequestBody HandleDataDTO handleDataDTO){
        return workspaceProcessService.agree(handleDataDTO);
    }

    /**
     * 委派按钮
     */
    @PostMapping("/delegateTask")
    public AjaxResult delegateTask(@RequestBody HandleDataDTO handleDataDTO){
        return workspaceProcessService.delegateTask(handleDataDTO);
    }

    /**
     * 委派人完成的按钮
     */
    @PostMapping("/resolveTask")
    public AjaxResult resolveTask(@RequestBody HandleDataDTO handleDataDTO){
        return workspaceProcessService.resolveTask(handleDataDTO);
    }


    /**
     * 拒绝的按钮
     */
    @PostMapping("/refuse")
    public AjaxResult refuse(@RequestBody HandleDataDTO handleDataDTO){
        return workspaceProcessService.refuse(handleDataDTO);
    }


    /**
     * 撤销的按钮
     */
    @PostMapping("/revoke")
    public AjaxResult revoke(@RequestBody HandleDataDTO handleDataDTO){
        return workspaceProcessService.revoke(handleDataDTO);
    }

    /**
     * 转办的按钮
     */
    @PostMapping("/assignee")
    public AjaxResult assignee(@RequestBody HandleDataDTO handleDataDTO){
        return workspaceProcessService.assignee(handleDataDTO);
    }

    /**
     * 查询可退回的节点(这个是给 下面 rollback接口作为入参用的
     */
    @PostMapping("/rollbackNodes")
    public AjaxResult rollbackNodes(@RequestBody HandleDataDTO handleDataDTO){
        Map<String, String> map = workspaceProcessService.rollbackNodes(handleDataDTO);
        return AjaxResult.success(map);
    }

    /**
     * 退回按钮
     */
    @PostMapping("/rollback")
    public AjaxResult rollback(@RequestBody HandleDataDTO handleDataDTO){
        return workspaceProcessService.rollback(handleDataDTO);
    }

    /**
     * 加签按钮
     */
    @PostMapping("/addMulti")
    public AjaxResult addMulti(@RequestBody HandleDataDTO handleDataDTO){
        return workspaceProcessService.addMulti(handleDataDTO);
    }

    /**
     * 通过流程实例查看审批记录
     */
    @PostMapping("/approve/record")
    public AjaxResult record (@RequestBody HandleDataDTO handleDataDTO){
        String processInstanceId = handleDataDTO.getProcessInstanceId();
        List<TaskDetailVO> taskDetailVOList = workspaceProcessService.record(processInstanceId);
        return AjaxResult.success(taskDetailVOList);
    }

    /**
     * 查看所有的流程
     */
    @PostMapping("/submitedTaskList")
    public TableDataInfo submitedTaskList (@RequestBody ApplyDTO applyDTO){
        List<HistoricProcessInstance> historicProcessInstances =
                historyService.createHistoricProcessInstanceQuery()
                        .includeProcessVariables()
                        .startedBy(applyDTO.getCurrentUserInfo().getId())
                        .orderByProcessInstanceStartTime().desc()
                        .listPage((applyDTO.getPageNo() - 1) * applyDTO.getPageSize(), applyDTO.getPageSize());
        long count = historyService.createHistoricProcessInstanceQuery()
                .startedBy(applyDTO.getCurrentUserInfo().getId()).count();
        List<HistoryProcessInstanceVO> historyProcessInstanceVOS = workspaceProcessService.submitedTaskList(historicProcessInstances);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(historyProcessInstanceVOS);
        rspData.setTotal(count);
        return rspData;
    }

    /**
     * 通过流程实例id查看详情
     */
    @PostMapping("/instanceInfo")
    public HandleDataVO instanceInfo(@RequestBody HandleDataDTO handleDataDTO){
        HandleDataVO handleDataVO = workspaceProcessService.instanceInfo(handleDataDTO);
        return handleDataVO;
    }

    /**
     * 删除审批(审批通过的页面上不展示删除按钮)
     */
    @DeleteMapping("/{processInstanceId}")
    public AjaxResult deleteProcessInstance(@RequestParam String processInstanceId){
        return workspaceProcessService.deleteProcessInstance(processInstanceId);
    }



}
